package cn.buyclss.backend.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;

public class JWTUtil {

    // 过期时间120分钟
    private static final long EXPIRE_TIME = 2 * 60 * 60 * 1000;

    public static final String JWT_CLAIM_KEY_UID = "uid";
    public static final String JWT_CLAIM_KEY_USERNAME = "username";
    public static final String JWT_CLAIM_KEY_USERTYPE = "usertype";
    public static final String SALT = "buyclss_backend";

    /**
     * 校验token是否正确
     *
     * @param token 密钥
     * @return 是否正确
     */
    public static boolean verify(String token, Integer uid, String username, Integer userType) {
        try {
            Algorithm algorithm = Algorithm.HMAC256(SALT);
            JWTVerifier verifier = JWT.require(algorithm)
                .withClaim(JWT_CLAIM_KEY_UID, uid)
                .withClaim(JWT_CLAIM_KEY_USERNAME, username)
                .withClaim(JWT_CLAIM_KEY_USERTYPE, userType)
                .build();
            DecodedJWT jwt = verifier.verify(token);
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */
    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的uid
     */
    public static String getUid(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("uid").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名,5min后过期
     *
     * @param username 用户名
     * @return 加密的token
     */
    public static String sign(Integer uid, String username, Integer userType) {
        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm = Algorithm.HMAC256(SALT);
            // 附带username信息
            return JWT.create()
                .withClaim(JWT_CLAIM_KEY_UID, uid)
                .withClaim(JWT_CLAIM_KEY_USERNAME, username)
                .withClaim(JWT_CLAIM_KEY_USERTYPE, userType)
                .withExpiresAt(date)
                .sign(algorithm);
        } catch (Exception e) {
            return null;
        }
    }

    public static void main(String[] args) {
//        String token = sign("shankai");
//        String u = getUsername(token);
//        System.out.println(token);
//        System.out.println(u);
    }
}
